#include "InfoDispatcher.hpp"

#include <QDebug>
#include <QFile>
#include <QMapIterator>
#include <QObject>
#include <QWebFrame>
#include <QVariant>


/*
  TODOS:
  - DONE - Polling interval.
  - Read Submit.js from file if there is one, otherwise read from Qt resource
  - Read webIDs from file ..
  - Read URL from file ..
  - EMail option
  */

namespace{
//const QString URL("http://www.comparis.ch/immobilien/default.aspx");
//const QString SUBMIT("ctl00_ctl02_usercontrol_btnShowResults");


const QString URL("http://www.comparis.ch/immobilien/marktplatz/search.aspx?searchtab=search&mode=expand");
const QString SUBMIT("ctl00_ContentPlaceHolderApplication_SearchControl_Search_btnSearch");
const QString TOWN_ID("ctl00_ContentPlaceHolderApplication_SearchControl_Search_txtTownOrPostalCode");

const QString RESULT_TITLE_ID("ctl00_ContentPlaceHolderApplication_ResultListUserControl_ResultListRepeater_ctl%0_ProductListResultItem_PropertyDetailsLabel"); /* %0 has to be replaced with a 00, 02, 04 etc */
const QString RESULT_PRICE_ID("ctl00_ContentPlaceHolderApplication_ResultListUserControl_ResultListRepeater_ctl%0_ProductListResultItem_PriceLabel"); /* %0 has to be replaced with a 00, 02, 04 etc */

const QString SCRIPT_NAME(":/Submit.js");
}

InfoDispatcher::InfoDispatcher()
{
   setupConnections();
   setupWebPage();

}

InfoDispatcher::~InfoDispatcher()
{

}


void InfoDispatcher::setupProperties()
{
   //Setup the properties from the ids list
   QMapIterator<QString, NamedPair> itr(ids);
   while(itr.hasNext())
   {
      itr.next();

      QString webKey = itr.key() + "_webID";
      setProperty(webKey.toUtf8(),QVariant(itr.value().id));

      QString webValue = itr.key() + "_webValue";
      setProperty(webValue.toUtf8(),QVariant(itr.value().value));
   }

   //Add additional properties like submit id
   setProperty("submit",QVariant(SUBMIT));
}

void InfoDispatcher::debug(const QString &value)
{
   qDebug("%s", qPrintable(value));
}

void InfoDispatcher::setupIDs()
{

      ids["town"] = NamedPair(TOWN_ID, m_town);

      setupProperties();

}

void InfoDispatcher::setupWebPage()
{
   QWebSettings *webSettings = page.settings();
   webSettings->setAttribute(QWebSettings::AutoLoadImages, false);
   webSettings->setAttribute(QWebSettings::PluginsEnabled, false);
   webSettings->setAttribute(QWebSettings::JavaEnabled, false);
   webSettings->setAttribute(QWebSettings::JavascriptEnabled, true);
   webSettings->setAttribute(QWebSettings::PrivateBrowsingEnabled,true);
}

void InfoDispatcher::setupConnections()
{
   connect(page.mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
           this, SLOT(injectJavaScriptIntoWindowObject()));
   connect(&page, SIGNAL(loadFinished(bool)),
           this, SLOT(supplyInfos(bool)));
}

void InfoDispatcher::injectJavaScriptIntoWindowObject()
{
   page.mainFrame()->addToJavaScriptWindowObject("info", this);
}

void InfoDispatcher::supplyInfos(bool ok)
{
   if (!ok) {
       emit finished(false);
       return;
   }
   QString javaScript = SCRIPT_NAME;
   if (SCRIPT_NAME.endsWith(".js")) {
       QFile file(SCRIPT_NAME);
       if (!file.open(QIODevice::ReadOnly)) {
           emit finished(false);
           return;
       }
       javaScript = QString::fromUtf8(file.readAll());
   }
   //qDebug() << "Javascript: " << javaScript;

   qDebug() << "The current id of town is: " << property("town_webID").toString();
   qDebug() << "The current value of town is: " << property("town_webValue").toString();
   QWebFrame *frame = page.mainFrame();
   frame->evaluateJavaScript(javaScript);
   emit finished(true);
   qDebug() << "Javascript evaluated!";
}

void InfoDispatcher::run()
{
   page.mainFrame()->load(URL);
}

void InfoDispatcher::setKeywords(const QString &town, float maxRent, float minRooms, const QString &type)
{
   m_town = town;
   m_maxRent = maxRent;
   m_minRooms = minRooms;
   m_type = type;

   setupIDs();
}


